import * as XLSX from 'xlsx';

export const readExcel = async file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = event => {
      const data = event.target.result;
      const workbook = XLSX.read(data, { type: 'binary' });

      const sheetName = workbook.SheetNames[0];
      const sheet = workbook.Sheets[sheetName];

      const json = XLSX.utils.sheet_to_json(sheet, { header: 1 });

      const questions = json
        .slice(1)
        .map(([question, answer, type, source, difficulty]) => ({
          question,
          answer,
          type,
          source,
          difficulty,
        }));

      resolve(questions);
    };

    reader.onerror = error => {
      reject(error);
    };

    reader.readAsBinaryString(file);
  });
};

export const readPresetExcel = async filePath => {
  return new Promise((resolve, reject) => {
    try {
      fetch(filePath)
        .then(response => response.blob())
        .then(blob => {
          const reader = new FileReader();
          reader.onload = e => {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const json = XLSX.utils.sheet_to_json(sheet);
            resolve(json);
          };
          reader.onerror = error => {
            reject(error);
          };
          reader.readAsArrayBuffer(blob);
        })
        .catch(error => {
          reject(error);
        });
    } catch (error) {
      reject(error);
    }
  });
};
